package com.yycwxt.modules.admin.dpyyfy_imp;

import com.yycwxt.common.ReturnResult;
import com.yycwxt.modules.admin.data_import.AccountData;
import com.yycwxt.modules.admin.data_import.ImpFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;

@RestController
@RequestMapping("/data_import")
@Api("数据导入")
public class DpyyfyController {
    private final DpyyfyService dpyyfyService;
    public DpyyfyController( DpyyfyService dpyyfyService){
        this.dpyyfyService=dpyyfyService;
    }

    @Value("${file.location}")
    String filelocation;
    @Value("${file.path}")
    String filepath;

    @PostMapping("/dpyyfy")
    @ApiOperation("店铺运营费用上传")
    public ReturnResult FileUpLoad(@ApiParam(value = "店铺运营费用excel文件", type = "_file") @RequestPart("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ReturnResult.buildFailureResult("文件为空");
        } else {
            try {
                // 保存文件
                // 服务器文件名
                String serverFilename = UUID.randomUUID().toString().substring(0, 8) + ".xlsx";
                // 创建目录
                String path = filelocation + AccountData.getAccountDate();
                System.out.println(path);
                Files.createDirectories(Paths.get(path));
                // 保存
                file.transferTo(Path.of(path, serverFilename));

                // 记录上传文件明细
                ImpFile impFile = new ImpFile();
                impFile.setFilename(file.getOriginalFilename());
                impFile.setName("店铺运营费用");
                impFile.setUrl("download/" + AccountData.getAccountDate() + "/" + serverFilename);
                impFile.setZq(AccountData.getAccountDate());
                impFile.setCreated(LocalDateTime.now());
                impFile.setRemark("店铺运营费用");
                System.out.println(impFile);
                dpyyfyService.save(impFile);

                // 解析excel，记录流水
                dpyyfyService.importDpyyfy(file);
                return ReturnResult.buildSuccessResult("导入成功", true);
            } catch (Exception e) {
                e.printStackTrace();
                return ReturnResult.buildFailureResult(e.toString());
            }
        }
    }
}

